﻿using Microsoft.EntityFrameworkCore;

using System;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;
using System.Text;
using System.Threading.Tasks;

using ZFB.Models;
using ZFB.Models.EntityConfig;
using ZFB.Repository.Extensions;

namespace ZFB.Repository.House
{
    public class HouseRepository : BaseRepository<T_Houses>, IHouseRepository
    {
        private readonly MyDbContext _dbContext;
        public HouseRepository(MyDbContext db) : base(db)
        {
            this._dbContext = db;
        }
        public override async Task<List<T_Houses>> GetListAsync(Expression<Func<T_Houses, bool>> whereExpression)
        {
            return await _dbContext.T_Houses
                 .AsNoTracking()
                 .Where(e => !e.IsDeleted)
                 .Include(e => e.T_Attachments)
                 .Include(e=>e.T_Communities.T_Regions.T_Cities)
                 .Include(e=>e.T_HousePics)
                 .Include(e=>e.T_IdNames)
                 .Include(e => e.T_IdNames1)
                 .Include(e => e.T_IdNames2)
                 .Include(e => e.T_IdNames3)
                 .Include(e => e.T_HouseAppointments)
                 .Where(whereExpression)
                 .ToListAsync();
        }
        public override async Task<Page<T_Houses>> GetPagesAsync(int page, int limit, Expression<Func<T_Houses, bool>> whereExpression)
        {
            Page<T_Houses> pages = new();
            var count = await _dbContext.T_Houses
                .AsNoTracking()
                .Where(e => !e.IsDeleted)
                .Where(whereExpression)
                .LongCountAsync();
            pages.Items = await _dbContext.T_Houses
                .AsNoTracking()
                .Where(e => !e.IsDeleted)
                .Include(e => e.T_Attachments)
                 .Include(e => e.T_Communities.T_Regions.T_Cities)
                 .Include(e => e.T_HousePics)
                 .Include(e => e.T_IdNames)
                 .Include(e => e.T_IdNames1)
                 .Include(e => e.T_IdNames2)
                 .Include(e => e.T_IdNames3)
                 .Include(e => e.T_HouseAppointments)
                .Where(whereExpression)
                .Skip((page - 1) * limit)
                .Take(limit)
                .ToListAsync();
            pages.TotalItems = count;
            pages.TotalPages = (int)Math.Ceiling(count * 10f / limit);
            pages.ItemsPerPage = limit;
            pages.CurrentPage = page;

            return pages;
        }
        public async override Task<T_Houses> GetModelAsync(Expression<Func<T_Houses, bool>> whereExpression)
        {
            return await _dbContext.T_Houses
                .Where(e => !e.IsDeleted)
                .Include(e => e.T_Attachments)
                .SingleOrDefaultAsync(whereExpression);
        }

    }
}
